chai = require 'chai'
chai.should()
sinon = require 'sinon'
should = require 'should'
mongodb = require('mongodb')

{MongoRepository} = require '../src/mongoRepository'

myObjectValue = {
  _id: '1234abcd1235'
  name: 'My name'
  message: 'My message.'
}
myObjectValueWithoutId = {
  name: 'My name'
  message: 'My message.'
  myObjectId: '1234NoId'
}
mongoServerName = 'mongosvc01-pod3.bvops.net'
databaseName = 'NodeTest'

dropDatabase = (done) ->
  mongoServer = new mongodb.Server mongoServerName, mongodb.Connection.DEFAULT_PORT, {}
  db = new mongodb.Db databaseName, mongoServer, {}
  db.open (err, client) ->
    if not err
      client.dropDatabase (err) ->
        done()

describe 'MongoDB Repository instance with object to store', ->

  mongoRepo = new MongoRepository(mongoServerName, databaseName, 'TestObject')

  it 'should store and retrieve value', (done)->
    myObjectValue.message = myObjectValue.message + Date.now()
    mongoRepo.set myObjectValue._id, myObjectValue, (err) ->
      should.not.exist err
      mongoRepo.get myObjectValue._id, (err, valueFromRepo)->
        valueFromRepo._id.should.equal myObjectValue._id
        done()

  it 'should remove value', (done) ->
    mongoRepo.set myObjectValue._id, myObjectValue, (setErr) ->
      should.not.exist setErr
      mongoRepo.remove myObjectValue._id, (removeErr) ->
        should.not.exist removeErr
        mongoRepo.get myObjectValue._id, (err, valueFromRepo) ->
          should.not.exist valueFromRepo
          done()

  it 'should find existing object with contains', (done) ->
    mongoRepo.set myObjectValue._id, myObjectValue, (err) ->
      should.not.exist err
      mongoRepo.contains myObjectValue._id, (err, isContained) ->
        should.not.exist err
        isContained.should.be.true
        done()

  it 'should return error when setting with a null key', (done) ->
    mongoRepo.set null, myObjectValue, (setErr) ->
      setErr.should.exist
      done()

  it 'should save and retrieve object without _id', (done) ->
    mongoRepo.set myObjectValueWithoutId.myObjectId, myObjectValueWithoutId, (setErr) ->
      should.not.exist setErr
      mongoRepo.get myObjectValueWithoutId.myObjectId, (getErr, document) ->
        should.not.exist getErr
        document.myObjectId.should.equal myObjectValueWithoutId.myObjectId
        done()

  afterEach (done) ->
    dropDatabase(done)

  beforeEach (done) ->
    dropDatabase(done)

